package com.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.qbb.client.bean.active.SocketBean;
import com.qbb.client.bean.result.SocketResultBean;
import com.qbb.client.exception.HandlerException;

/**
 * @author 作者 : 陈怀傲
 * @version 创建时间：2015年4月14日 上午9:11:11 类说明
 */
public class QbbThreadCall {
	private static Log log = LogFactory.getLog(QbbThreadCall.class);

	private String host;
	private Integer port;
	private SocketBean socketBean;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public SocketBean getSocketBean() {
		return socketBean;
	}

	public void setSocketBean(SocketBean socketBean) {
		this.socketBean = socketBean;
	}

	/**
	 * 启动监听服务
	 * 
	 * @param host
	 * @param port
	 * @param socketBean
	 * @return
	 */
	public Map<String, Object> runStart() {
		// 控制多线程调用,操作连接数量的控制
		String uuid = socketBean.getUuid();

		synchronized (QbbClient.activeQueue) {
			boolean flag = QbbClient.activeQueue.offer(uuid);
			if (!flag) {
				return HandlerException
						.returnMsg("QbbClient-activeQueue-[队列已满]");
			}
		}

		String activeResource = socketBean.toString();
		QbbClient.activeMaps.put(uuid, activeResource);

		Bootstrap bootstrap = null;
		EventLoopGroup workerGroup = null;
		try {
			bootstrap = new Bootstrap();
			workerGroup = new NioEventLoopGroup();

			bootstrap.group(workerGroup);
			bootstrap.channel(NioSocketChannel.class); // (3)
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.handler(new ClientChannelInitializer());
			// Start the client.
			ChannelFuture f = bootstrap.connect(host, port).sync(); // (5)

			// Wait until the connection is closed.
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			HandlerException.error(e);

			QbbClient.activeQueue.remove(uuid);
			QbbClient.activeMaps.remove(uuid);
			QbbClient.readMaps.remove(uuid);

			return HandlerException.returnMsg("客户端无法连接IP和端口!"
					+ socketBean.getServerName() + ",ip:" + host + ",port:"
					+ port + "]");
		} finally {
			if (workerGroup != null) {
				workerGroup.shutdownGracefully();
			}
		}

		SocketResultBean resultBean = QbbClient.readMaps.get(uuid);
		QbbClient.readMaps.remove(uuid);
		if (resultBean == null) {
			return HandlerException.returnMsg("调用qbbserver存在错误信息");
		}
		Map<String, Object> resultMap = resultBean.getResult();

		return resultMap;
	}
}
